package com.googlecode.theta.server;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.DefaultServlet;
import org.mortbay.jetty.servlet.ServletHolder;

public class WebServer {
  private final int port;
  private final Context servletContext;
  private final Server server;

  public WebServer(int port, String resourceBase) {
    this.port = port;
    server = new Server(port);
    servletContext = new Context(getServer(), "/", true, false);
    servletContext.setResourceBase(resourceBase);
    servletContext.addServlet(new ServletHolder(new DefaultServlet()), "/");
  }

  void run() {
    try {
      getServer().start();

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
    /*server.addHandler(new AbstractHandler() {
             public void handle(String target, HttpServletRequest request,
                     HttpServletResponse response, int dispatch)
                     throws IOException, ServletException {
                 Object m = globalScope.get("main", globalScope);
                 if(m instanceof Function) {
                     Object result = ((Function) m).call(context, globalScope, globalScope, new Object[] { target, request, response });
                     if(result != null && result instanceof Boolean && ((Boolean)result) == true) {
                         ((Request)request).setHandled(true);
                     }
                 } else {
                     System.err.println("Main not found.");
                 }
             }
         });*/
  }

  public void stop() {
    try {
      server.stop();
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.exit(0);
  }

  public int getPort() {
    return port;
  }

  public Context getContext() {
    return servletContext;
  }

  public Server getServer() {
    return server;
  }
}
